package cn.com.cloudpioneer.evaluate.service;

import cn.com.cloudpioneer.evaluate.mapper.RoleMapper;
import cn.com.cloudpioneer.evaluate.mapper.UserMapper;
import cn.com.cloudpioneer.evaluate.model.RoleModel;
import cn.com.cloudpioneer.evaluate.model.UserModel;
import cn.com.cloudpioneer.evaluate.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @auther maruikai
 * @create 2023/9/14-10:37
 */
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Autowired
    private RedisService redisService;

    @Value("${evaluate.user.password}")
    private String initialPwd;


    @Transactional(rollbackFor = Exception.class)
    public Object setUser(String userName, String loginName, String roleIds) throws CustomException {
        if (StringUtil.isEmpty(loginName)) {
            throw new CustomException(5003, "用户名不能为空");
        }
        if (StringUtil.isEmpty(roleIds)) {
            throw new CustomException(5003, "用户权限不能为空");
        }
        UserModel one = userMapper.findOne(loginName, initialPwd);
        if (one != null) {
            throw new CustomException(5003, "该用户已存在,请重新填写登录账号名信息！");
        }
        UserModel userModel = new UserModel();
        userModel.setUserId(Generate.generateId());
        userModel.setLoginName(loginName);
        userModel.setPassword(initialPwd);
        if (roleIds.equals("1")){
            userModel.setAdminFlag(true);
        }
        userModel.setRoleIds(roleIds);
        userModel.setUserName(StringUtil.isEmpty(userName) ? userModel.getLoginName() : userName);
        Integer integer = userMapper.addUser(userModel);
        if (integer < 0) throw new CustomException(5001, "操作失败");
        return integer;
    }

    public Object loginUser(String loginName, String password) throws CustomException {
        UserModel one = userMapper.findOne(loginName, password);
        if (one == null) {
            throw new CustomException(5004, "用户名、密码错误");
        }
        List<String> strings = new ArrayList<>(Arrays.asList(one.getRoleIds().split(",")));
        List<RoleModel> byIds = roleMapper.findByIds(strings);
        one.setRoleList(byIds);
        String jwt = JwtUtils.createJwt(one);
        one.setToken(jwt);
        this.setRedis(jwt);
        return one;
    }

    public Object updatePassword(UserModel userModel) throws CustomException {
        UserModel one = userMapper.findOne(userModel.getLoginName(), userModel.getPassword());
        if (one == null) {
            throw new CustomException(5004, "旧密码错误");
        }
        if (!one.getUserId().equals(userModel.getUserId())) {
            throw new CustomException(5004, "用户id错误");
        }
        one.setPassword(userModel.getNewPassword());
        return userMapper.updateUser(one);
    }

    public Object getUserList(String keyword, int pageNo, int pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<UserModel> all = userMapper.findAllByKeyword(keyword);
        for (UserModel userModel : all) {
            List<String> strings = new ArrayList<>(Arrays.asList(userModel.getRoleIds().split(",")));
            List<RoleModel> byIds = roleMapper.findByIds(strings);
            userModel.setRoleList(byIds);
        }
        return new PageInfo<>(all);
    }

    public Object getAppraiserUserList() {
        return userMapper.findAll();
    }

    public Object updateUserRole(UserModel userModel) throws CustomException {
        UserModel byUserId = userMapper.findByUserId(userModel.getUserId());
        if (byUserId == null) {
            throw new CustomException(5005, "获取用户信息错误");
        }
        BeanUtils.copyProperties(userModel,byUserId);
        if (userModel.getRoleList().size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (RoleModel roleModel : userModel.getRoleList()) {
                stringBuilder.append(roleModel.getRoleId()).append(",");
            }
            byUserId.setRoleIds(stringBuilder.toString());
        }
        return userMapper.updateUser(byUserId);
    }

    private void setRedis(String token) {
        String tokenKey = "evaluate:user:token::" + token;
        redisService.objectSet(tokenKey, token);
        redisService.expireKey(tokenKey, Values.EXPIRE_TIME);
    }

    public Object delUser(String userId) throws CustomException {
        UserModel byUserId = userMapper.findByUserId(userId);
        if (byUserId == null) {
            throw new CustomException(5005, "获取用户信息错误");
        }
        return userMapper.delUser(userId);
    }

    public Object roleList() {

        return roleMapper.findAll();
    }
}
